package com.example.bankmanage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bankmanage.dto.rep.*;
import com.example.bankmanage.entity.PageBean;
import com.example.bankmanage.entity.bills;
import com.example.bankmanage.result.Result;
import com.example.bankmanage.service.BillService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.time.LocalDate;

//import static cn.hutool.http.ContentType.JSON;

@RestController
@RequestMapping("/bill")
@Slf4j
public class BillController {
    @Autowired
    private BillService billService;

    @PostMapping("/getBillList")
    public Result<PageBean> getBillList(@RequestBody GetBillListReqDTO requestParam) {
        PageBean<bills> pageBean = billService.getBillList(requestParam);
        return Result.success(pageBean);
    }

    @PostMapping("/addBill")
    public Result addBill(@RequestBody AddBillReqDTO requestParam) {
        billService.addBill(requestParam);
        return Result.success("添加交易成功");
    }

    @PutMapping("/updateBill")
    public Result updateBill(@RequestParam Integer billId, @RequestBody UpdateBillReqDTO requestParam) {
        log.info("修改交易已经执行");
        billService.updateBill(billId, requestParam);
        return Result.success();
    }

    @DeleteMapping("/deleteBill")
    public Result deleteBill(@RequestParam Integer billId) {
        billService.deleteBill(billId);
        return Result.success();
    }

    @GetMapping("/exportBill")
    public void exportBill(
            @RequestParam(required = false) Integer billType,
            @RequestParam(required = false) Integer paymentStatus,
            @RequestParam(required = false) Long accountId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletResponse response) throws IOException {

        log.info("导出参数: billType={}, paymentStatus={}, accountId={}, startDate={}, endDate={}",
                billType, paymentStatus, accountId, startDate, endDate);

        // 关键修改1: 确保在异常时重置response
        response.reset();

        try {
            // 1. 构建查询参数
            BillExportReqDTO exportDTO = new BillExportReqDTO();
            exportDTO.setBillType(billType);
            exportDTO.setPaymentStatus(paymentStatus);
            exportDTO.setAccountId(accountId);

            // 日期转换处理
            if (StringUtils.isNotBlank(startDate)) {
                try {
                    exportDTO.setStartDate(Date.valueOf(startDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("开始日期格式不正确，应为YYYY-MM-DD");
                }
            }
            if (StringUtils.isNotBlank(endDate)) {
                try {
                    exportDTO.setEndDate(Date.valueOf(endDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("结束日期格式不正确，应为YYYY-MM-DD");
                }
            }

            // 2. 设置响应头
            String fileName = "账单_" + LocalDate.now() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 3. 导出Excel
            billService.exportBill(exportDTO, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            log.error("导出Excel失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(JSON.toJSONString(Result.error("导出失败: " + e.getMessage())));
        }
//        return Result.success();
    }
}
//        return response
